#include "stdafx.h"
#include "ErrorBase.h"

#ifdef WIN32
#include <lmerr.h>
std::string GetErrorText( DWORD dwLastError )
{
    HMODULE hModule = NULL; // default to system source
    LPSTR MessageBuffer;
    DWORD dwBufferLength;
    std::string	ErrorText;

    DWORD dwFormatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_IGNORE_INSERTS |
        FORMAT_MESSAGE_FROM_SYSTEM ;

    // If dwLastError is in the network range, 
    //  load the message source.

    if(dwLastError >= NERR_BASE && dwLastError <= MAX_NERR) {
        hModule = LoadLibraryEx(
            TEXT("netmsg.dll"),
            NULL,
            LOAD_LIBRARY_AS_DATAFILE
            );

        if(hModule != NULL)
            dwFormatFlags |= FORMAT_MESSAGE_FROM_HMODULE;
    }

    // Call FormatMessage() to allow for message 
    //  text to be acquired from the system 
    //  or from the supplied module handle.

    if(dwBufferLength = FormatMessageA(
        dwFormatFlags,
        hModule, // module to get message from (NULL == system)
        dwLastError,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // default language
        (LPSTR) &MessageBuffer,
        0,
        NULL
        ))
    {
        //DWORD dwBytesWritten;

        ErrorText.append(MessageBuffer, dwBufferLength);
        // Output message string on stderr.
        /*
        WriteFile(
            GetStdHandle(STD_ERROR_HANDLE),
            MessageBuffer,
            dwBufferLength,
            &dwBytesWritten,
            NULL
            );
        */

        // Free the buffer allocated by the system.
        LocalFree(MessageBuffer);
    }

    // If we loaded a message source, unload it.
    if(hModule != NULL)
        FreeLibrary(hModule);
    
    return ErrorText;
}
#endif
